//
//  HXDPlusView.swift
//  weibo
//
//  Created by huxuedong on 15/12/12.
//  Copyright © 2015年 huxuedong. All rights reserved.
//

import UIKit
import pop

class HXDPlusView: UIView {

    var target: UIViewController?
    private var plusButtonInfos: [HXDPlusButtonInfo]?
    
    private lazy var bgImageView: UIImageView = UIImageView(image: UIImage.cutOffPicture().applyLightEffect())
    private lazy var sloganImageView: UIImageView = UIImageView(image: UIImage(named: "compose_slogan"))
    private lazy var buttons: [HXDPlusMenuButton] = [HXDPlusMenuButton]()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        width = kScreenW
        height = kScreenH
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() {
        addSubview(bgImageView)
        addSubview(sloganImageView)
        bgImageView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(self).offset(UIEdgeInsetsZero)
        }
        sloganImageView.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(self)
            make.top.equalTo(self).offset(100)
        }
        addSubButton()
    }
    
    private func addSubButton() {
        let subW: CGFloat = 80
        let subH: CGFloat = 110
        let column: CGFloat = 3
        let margin: CGFloat = (kScreenW - column * subW) / (column + 1)
        plusButtonInfos = getButtonInfos()
        //获取数组中元素的元组信息
        for (i, value) in plusButtonInfos!.enumerate() {
            let button = HXDPlusMenuButton()
            button.addTarget(self, action: "subButtonAction:", forControlEvents: .TouchUpInside)
            button.tag = i
            let icon = value.icon!
            let title = value.title!
            button.setImage(UIImage(named: icon), forState: .Normal)
            button.setTitle(title, forState: .Normal)
            button.size = CGSize(width: subW, height: subH)
            let rowIndex = i / Int(column)
            let columnIndex = i % Int(column)
            button.x = CGFloat(columnIndex + 1) * margin + CGFloat(columnIndex) * subW
            button.y = CGFloat(rowIndex) * (margin + subH) + kScreenH
            addSubview(button)
            buttons.append(button)
        }
    }
    
    private func getButtonInfos() -> [HXDPlusButtonInfo] {
        let path = NSBundle.mainBundle().pathForResource("plus", ofType: "plist")!
        let array = NSArray(contentsOfFile: path)!
        //实例化按钮信息模型数组
        var plusButtonInfos = [HXDPlusButtonInfo]()
        for value in array {
            //将字典转换为模型并添加到数组中
            plusButtonInfos.append(HXDPlusButtonInfo(dict: value as! [String: AnyObject]))
        }
        return plusButtonInfos
    }
    
    @objc private func subButtonAction(button: UIButton) {
        UIView.animateWithDuration(0.5, animations: { () -> Void in
            //遍历每一个按钮
            for value in self.buttons {
                value.alpha = 0.3
                //如果为点击的按钮
                if value == button {
                    value.transform = CGAffineTransformMakeScale(2, 2)
                } else {
                    value.transform = CGAffineTransformMakeScale(0.3, 0.3)
                }
            }
        }) { (_) -> Void in
            let info = self.plusButtonInfos![button.tag]
            if let name = info.className {
                let classer = NSClassFromString(name) as? UIViewController.Type
                let classObject = classer?.init()
                //跳转到plusController控制器
                self.target?.presentViewController(HXDNavigationController(rootViewController: classObject!), animated: true, completion: { () -> Void in
                    //将当前plusView移除
                    self.removeFromSuperview()
                })
            }
        }
    }
    
    private func animation(button: UIButton, isUp: Bool = true, index: Int) {
        //利用第三方框架创建动画
        let animation = POPSpringAnimation(propertyNamed: kPOPViewCenter)
        let y: CGFloat = isUp ? button.center.y - 350 : button.center.y + 350
        //设置每个按钮将要运动到的位置坐标
        animation.toValue = NSValue(CGPoint: CGPoint(x: button.center.x, y: y))
        //弹性幅度
        animation.springBounciness = 8
        //弹动速度
        animation.springSpeed = 10
        //开始时间
        animation.beginTime = CACurrentMediaTime() + Double(index) * 0.025
        //为每个按钮添加动画
        button.pop_addAnimation(animation, forKey: nil)
    }
    
    func show(target: UIViewController?) {
        self.target = target
        //添加当前plusView到目标控制器
        target?.view.addSubview(self)
        for (i, value) in buttons.enumerate() {
            //遍历按钮，执行动画
            animation(value, index: i)
        }
    }
    
    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        //点击屏幕，倒序遍历按钮，执行动画
        for (i, value) in buttons.reverse().enumerate() {
            animation(value, isUp: false, index: i)
        }
        //0.3秒后将plusView从目标控制器中移除
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(0.3 * Double(NSEC_PER_SEC))), dispatch_get_main_queue(), { () -> Void in
            self.removeFromSuperview()
        })
    }

}
